package cn.dslcode.security.controller;

import cn.dslcode.common.web.response.RestResponse;
import cn.dslcode.security.common.DataCenter;
import cn.dslcode.security.common.SystemUser;
import cn.dslcode.security.common.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@Slf4j
@RestController
public class UserController {

    @GetMapping("user/list")
    @PreAuthorize("hasAuthority('USER_VIEW')")
    public RestResponse userList() {
        SystemUser currentUser = UserUtil.getCurrentUser();
        log.info("userList.currentUser={}", currentUser);
        return RestResponse.buildSuccessData(DataCenter.users);
    }

    @PostMapping("user/edit")
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public RestResponse userEdit() {
        return RestResponse.buildSuccessData(DataCenter.users);
    }

    @PostMapping("user/authority/edit")
    @PreAuthorize("hasRole('ROLE_ADMIN')") // 必须以ROLE_开头
    public RestResponse userAuthorityEdit() {
        Authentication authentication = DataCenter.authenticationMap.get("user");
        if (authentication != null) {
            // 踢人
            authentication.setAuthenticated(false);
            SystemUser userDetails = DataCenter.users.stream().filter(u -> u.getUsername().equals("user")).findFirst().orElse(null);
            Collection<GrantedAuthority> grantedAuthorities = (Collection<GrantedAuthority>) userDetails.getAuthorities();
            grantedAuthorities.add(new SimpleGrantedAuthority("USER_EDIT"));
            return RestResponse.buildSuccess();
        }
        return RestResponse.buildFail("该用户处于离线状态");
    }



}